//η φόρμα που δμιουργεί-τροποποιεί καλλιτέχνες
//author: Κωνσταντίνα Πολυχρονοπούλου
package artist;

import java.util.Iterator;
import java.util.List;
import javax.persistence.Query;
import javax.swing.JFrame;
import radiostation_POJOS.Musicgenre;
import radiostation_POJOS.Artist;
import javax.swing.JOptionPane;
import radiostation.DBManager;

public class NewOrModifyArtistForm extends javax.swing.JFrame {
    Long id;
    boolean mod;
    Artist a;
    
    //constructor
    public NewOrModifyArtistForm(Artist a,boolean mod) {
        DBManager.openConnection();
        this.a=a;
        this.mod=mod;
        initComponents();
        setLocationRelativeTo(null);
        setSexComboBox();
         //εδώ ανοίγω connection με τη βαση για να γεμισω τα combos
        Query q;
        q = DBManager.getEm().createQuery("SELECT mg FROM Musicgenre mg ", Musicgenre.class);
        List result = q.getResultList();
        if (!result.isEmpty()) { // βρήκα τη μέθοδο από το ίντερνετ
            Iterator itr=result.iterator();
            while (itr.hasNext()){
                Musicgenre mg = (Musicgenre)itr.next();
                Musicgenre_ComboBox.addItem(mg);
            }
        }
         if (a!=null){//αν μεταβάλεις τον επιλεγμένο καλλιτέχνη
            FirstName.setText(a.getFirstname());
            LastName.setText(a.getLastname());
            Artisticname.setText(a.getArtisticname());
            birthplace.setText(a.getBirthplace());
            jDateChooser1.setDate(a.getBirthday()); 
            Sex_ComboBox.setSelectedItem(a.getSex());
            Musicgenre_ComboBox.setSelectedItem(a.getFkMusicgenreId());
            setTitle("Τροποποίηση στοιχείων καλλιτέχνη");
            jLabel1.setText("Παρακαλώ τροποποιήστε τα στοιχεία του καλλιτέχνη:");
         }
         else{//αν ο καλλιτέχνης είναι καινούργιος
            this.a=new Artist();   
        }
        } 

    private void setSexComboBox () {
        /* Πρoσθηκη των τιμών στο list του Sex */
        this.Sex_ComboBox.addItem("Aνδρας");
        this.Sex_ComboBox.addItem("Γυναίκα");
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        RadiostationPUEntityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("RadiostationPU").createEntityManager();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        FirstName = new javax.swing.JTextField();
        LastName = new javax.swing.JTextField();
        Artisticname = new javax.swing.JTextField();
        birthplace = new javax.swing.JTextField();
        insert = new javax.swing.JButton();
        cancel = new javax.swing.JButton();
        Musicgenre_ComboBox = new javax.swing.JComboBox();
        Sex_ComboBox = new javax.swing.JComboBox();
        jDateChooser1 = new com.toedter.calendar.JDateChooser();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Δημιουργία Νέου Καλλιτέχνη");
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });

        jLabel1.setBackground(new java.awt.Color(204, 204, 255));
        jLabel1.setFont(new java.awt.Font("Monotype Corsiva", 1, 14)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(0, 0, 255));
        jLabel1.setText("  Παρακαλώ  εισάγετε  τα  στοιχεία  του  νέου καλλιτέχνη:");

        jLabel2.setFont(new java.awt.Font("Calibri", 0, 12)); // NOI18N
        jLabel2.setText("Όνομα:");

        jLabel3.setFont(new java.awt.Font("Calibri", 0, 12)); // NOI18N
        jLabel3.setText("Επώνυμο:");

        jLabel4.setFont(new java.awt.Font("Calibri", 0, 12)); // NOI18N
        jLabel4.setText("Καλλιτεχνικό όνομα(*):");

        jLabel5.setFont(new java.awt.Font("Calibri", 0, 12)); // NOI18N
        jLabel5.setText("Ημερομηνία Γέννησης(*):");

        jLabel6.setFont(new java.awt.Font("Calibri", 0, 12)); // NOI18N
        jLabel6.setText("Είδος μουσικής:");

        jLabel7.setFont(new java.awt.Font("Calibri", 0, 12)); // NOI18N
        jLabel7.setText("Τόπος Γέννησης (*):");

        jLabel8.setFont(new java.awt.Font("Calibri", 0, 12)); // NOI18N
        jLabel8.setText("Φύλο (*):");

        jLabel10.setText("(*) Προαιρετικά στοιχεία");

        FirstName.setFont(new java.awt.Font("Calibri", 0, 12)); // NOI18N

        LastName.setFont(new java.awt.Font("Calibri", 0, 12)); // NOI18N

        Artisticname.setFont(new java.awt.Font("Calibri", 0, 12)); // NOI18N
        Artisticname.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ArtisticnameActionPerformed(evt);
            }
        });

        birthplace.setFont(new java.awt.Font("Calibri", 0, 12)); // NOI18N

        insert.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Check.png"))); // NOI18N
        insert.setText("Αποθήκευση");
        insert.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                insertActionPerformed(evt);
            }
        });

        cancel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Cancel.png"))); // NOI18N
        cancel.setText("Ακύρωση");
        cancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelActionPerformed(evt);
            }
        });

        Musicgenre_ComboBox.setFont(new java.awt.Font("Calibri", 0, 12)); // NOI18N
        Musicgenre_ComboBox.setToolTipText("");
        Musicgenre_ComboBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                Musicgenre_ComboBoxActionPerformed(evt);
            }
        });

        Sex_ComboBox.setFont(new java.awt.Font("Calibri", 0, 12)); // NOI18N
        Sex_ComboBox.setToolTipText("");

        jDateChooser1.setDateFormatString("yyyy-MM-dd");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(39, 39, 39)
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 432, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addGroup(layout.createSequentialGroup()
                            .addGap(82, 82, 82)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addComponent(jLabel5)
                                .addComponent(jLabel7))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(jDateChooser1, javax.swing.GroupLayout.PREFERRED_SIZE, 199, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(cancel)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(98, 98, 98)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                            .addComponent(jLabel4)
                                            .addComponent(jLabel6)
                                            .addComponent(jLabel8)
                                            .addComponent(insert)))
                                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                        .addContainerGap()
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                            .addComponent(jLabel2)
                                            .addComponent(jLabel3))))
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(10, 10, 10)
                                        .addComponent(jLabel10))
                                    .addComponent(Musicgenre_ComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(Artisticname, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(Sex_ComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(LastName, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(FirstName, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(birthplace, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {cancel, insert});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(FirstName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(LastName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(Artisticname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel5)
                    .addComponent(jDateChooser1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7)
                    .addComponent(birthplace, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel8)
                    .addComponent(Sex_ComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(Musicgenre_ComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel10)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(insert)
                    .addComponent(cancel))
                .addGap(22, 22, 22))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void insertActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_insertActionPerformed
        // αποθήκευση καλλιτεχνών
        if (!DBManager.getEm().getTransaction().isActive()){
            DBManager.getEm().getTransaction().begin();
        }
        if ( FirstName.getText().isEmpty() || LastName.getText().isEmpty()) {
            JOptionPane.showMessageDialog(null, "Τα πεδία επώνυμο και όνομα είναι υποχρεωτικά!", "Σφάλμα", JOptionPane.ERROR_MESSAGE);
        } else {
        try{//εδώ όταν έχω τροποποίηση
            if(this.mod){//για να είναι managed
            Artist a2= DBManager.getEm().createNamedQuery("Artist.findByArtistId", Artist.class).setParameter("artistId", this.a.getArtistId()).getSingleResult();
            a2.setFirstname(FirstName.getText());
            a2.setLastname(LastName.getText());
            a2.setArtisticname(Artisticname.getText());
            a2.setBirthday(jDateChooser1.getDate());
            a2.setBirthplace(birthplace.getText());
            a2.setSex((String)Sex_ComboBox.getSelectedItem());
            a2.setFkMusicgenreId((Musicgenre)Musicgenre_ComboBox.getSelectedItem());            
            ListArtistForm.artistList.set(ListArtistForm.ArtistTable.getSelectedRow(),a2);
            }//εδώ όταν έχω καινούργιο
            this.a.setFirstname(FirstName.getText());
            this.a.setLastname(LastName.getText());           
            this.a.setArtisticname(Artisticname.getText());                
            this.a.setBirthday(jDateChooser1.getDate());
            this.a.setBirthplace(birthplace.getText());
            this.a.setSex((String)Sex_ComboBox.getSelectedItem());
            this.a.setFkMusicgenreId((Musicgenre)Musicgenre_ComboBox.getSelectedItem());
            if(!this.mod){
                DBManager.getEm().persist(this.a);//προσθήκη στη transaction με τη βάση
                ListArtistForm.artistList.add(this.a);
            }
                DBManager.getEm().getTransaction().commit();//πραγματοποίηση αλλαγών στη βάση
                this.dispose();//kleisimo formas
        } catch (Exception e) {
            e.printStackTrace();
            DBManager.getEm().getTransaction().rollback();
        } 
        }
    }//GEN-LAST:event_insertActionPerformed
    
    private void cancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelActionPerformed
        // TODO add your handling code here:
        dispose();
    }//GEN-LAST:event_cancelActionPerformed

    private void ArtisticnameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ArtisticnameActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_ArtisticnameActionPerformed

    private void Musicgenre_ComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Musicgenre_ComboBoxActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_Musicgenre_ComboBoxActionPerformed

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
        // όταν κλείνει το παράθυρο
        ListArtistForm ListArtistForm = new ListArtistForm(); 
        ListArtistForm.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 
        ListArtistForm.setVisible(true);  
    }//GEN-LAST:event_formWindowClosed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(NewOrModifyArtistForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NewOrModifyArtistForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NewOrModifyArtistForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NewOrModifyArtistForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NewOrModifyArtistForm(null,false).setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField Artisticname;
    private javax.swing.JTextField FirstName;
    private javax.swing.JTextField LastName;
    private javax.swing.JComboBox Musicgenre_ComboBox;
    private javax.persistence.EntityManager RadiostationPUEntityManager;
    private javax.swing.JComboBox Sex_ComboBox;
    private javax.swing.JTextField birthplace;
    private javax.swing.JButton cancel;
    private javax.swing.JButton insert;
    private com.toedter.calendar.JDateChooser jDateChooser1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    // End of variables declaration//GEN-END:variables
}
